package com.wo.cloud.auth.sms;

import com.wo.cloud.auth.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.config.annotation.SecurityConfigurerAdapter;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.web.DefaultSecurityFilterChain;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;
import org.springframework.stereotype.Component;

/**
 * @author liry
 * @version 1.0
 * @date Created on 2021/5/25 11:20
 * Description: 手机验证码登录方式 配置
 */

@Component
@Configuration
@EnableWebSecurity
public class SmsCodeAuthenticationSecurityConfig
        extends SecurityConfigurerAdapter<DefaultSecurityFilterChain, HttpSecurity> {

    @Autowired
    private UserService userService;

    @Override
    public void configure(HttpSecurity builder) throws Exception {

        // 配置过滤器
        SmsCodeAuthenticationFilter smsCodeAuthenticationFilter = new SmsCodeAuthenticationFilter();
        smsCodeAuthenticationFilter.setAuthenticationManager(builder.getSharedObject(AuthenticationManager.class));

        // 获取验证码提供者
        SmsCodeAuthenticationProvider authenticationProvider = new SmsCodeAuthenticationProvider(userService);


        // 将短信验证码添加到 httpsecurity ， 并在短信验证之后进行 UsernamePasswordAuthenticationFilter 验证
        builder.authenticationProvider(authenticationProvider)
                .addFilterAfter(smsCodeAuthenticationFilter, UsernamePasswordAuthenticationFilter.class);
    }
}
